package lc2;

import java.util.ArrayList;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;


import org.junit.Test;

public class Ex468 {
    class Solution {
        public String validIPAddress(String queryIP) {
            if (validIPV4(queryIP)) {
                return "IPv4";
            } else if (validIPV6(queryIP)) {
                return "IPv6";
            } else {
                return "Neither";
            }
        }

        private boolean validIPV6(String ip) {
            if (ip.startsWith(":") || ip.endsWith(":")) {
                return false;
            }
            String[] ss = ip.split(":");
            if (ss.length != 8) {
                return false;
            }
            for (int i = 0; i < 8; i++) {
                if (!validV6Seg(ss[i])) {
                    return false;
                }
            }
            return true;
        }

        private boolean validV6Seg(String s) {
            int n = s.length();
            if (!(1 <= n && 4 >= n)) {
                return false;
            }
            for (char c: s.toCharArray()) {
                if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
                    return false;
                }
            }
            return true;
        }

        private boolean validIPV4(String ip) {
            if (ip.startsWith(".") || ip.endsWith(".")) {
                return false;
            }
            String[] ss = ip.split("\\.");
            if (ss.length != 4) {
                return false;
            }
            for (String s: ss) {
                if (!validNum(s)) {
                    return false;
                }
            }
            return true;
        }

        //"20EE:FGb8:85a3:0:0:8A2E:0370:7334"
        private boolean validNum(String s) {
            int n = s.length();
            if (n > 3 || n < 1) {
                return false;
            }
            char[] cs = s.toCharArray();
            if (n > 1 && cs[0] == '0') {
                return false;
            }
            int res = 0;
            for (int i = 0; i < n; i++) {
                if (cs[i] < '0' || cs[i] > '9') {
                    return false;
                }
                res = res * 10 + (cs[i] - '0');
            }
            return res < 256;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        System.out.println(s.validIPAddress("192.0.0.1."));   
        // x0, 1, x2, 3, 4
    }
}
